"""Main product initializer
"""

from Products.CMFPlone.utils import getToolByName
from Products.CMFCore.Expression import Expression
from apkn.workspaces.config import WORKSPACE_GROUP_ID
from Products.CMFPlacefulWorkflow.PlacefulWorkflowTool import \
                                                WorkflowPolicyConfig_id
import logging

PRODUCTS_TO_INSTALL = ('Scrawl',)
BLOG_TYPE_META = 'Blog Entry'
BLOG_TYPE_ICON_EXPR = 'string:${portal_url}/++resource++apkn.workspaces.media/icons/blog.png'
WORKSPACE_POLICY_ID = 'apkn_workspace_placeful_policy'

def import_various(context):
    install_scrawl(context)
    fix_blog_entry_type(context)
    create_workspace_group(context)
    update_workflow_policies(context)
    return

def install_scrawl(context):
    site = context.getSite()
    qi = getToolByName(site, 'portal_quickinstaller', None)
    
    if qi is not None:
        for product in PRODUCTS_TO_INSTALL:
            if not qi.isProductInstalled(product):
                try:
                    qi.installProduct(product)
                    logging.info("Finished installing %s", product)
                except Exception, e:
                    logging.error("Failed to install %s. Error %s",
                    product, e.__str__())
    else:
        logging.error("Unable to acquire portal_quickinstaller tool")
    return

def fix_blog_entry_type(context):
    '''
    Fix missing blog entry type
    '''
    # TODO Make this update finalize icon_expr_object as well
    return
    
    site = context.getSite()
    pt = getToolByName(site, 'portal_types', None)
    
    if pt is not None:
        if hasattr(pt, BLOG_TYPE_META):
            blog_entry_type = getattr(pt, BLOG_TYPE_META)
            if not blog_entry_type.icon_expr:
                blog_entry_type.icon_expr_object = \
                                    Expression(BLOG_TYPE_ICON_EXPR)
                logging.info("Updated blog type icon expression property")
            else:
                logging.info("Blog entry already has icon expression")
        else:
            logging.info("%s is not among installed portal types",
            BLOG_TYPE_META)
    else:
        logging.error("Unable to acquire portal_types tool")
    return

def create_workspace_group(context):
    '''
    Create the group of workspace contributors
    '''
    site = context.getSite()
    group_tool = getToolByName(site, 'portal_groups', None)
    if group_tool:
        logging.info('Creating workspace group')
        if group_tool.isGroup(WORKSPACE_GROUP_ID):
            logging.info('Group already exists. Will not create.')
        else:
            try:
                group_tool.addGroup(WORKSPACE_GROUP_ID)
                logging.info('Created group')
            except Exception, e:
                logging.error('Failed to create group - Error %s',
                e.__str__()
                )
    else:
        logging.error('Unable to acquire group tool')
    return


def update_workflow_policies(context):
    site = context.getSite()
    
    placeful_workflow_tool = getToolByName(site, 'portal_placeful_workflow', None)
    catalog = getToolByName(site, 'portal_catalog', None)
    
    # update workflow configurations 
    if placeful_workflow_tool is not None:
        if catalog is not None:
            for workspace in catalog(portal_type = 'WorkSpace'):
                ws_object = workspace.getObject()
                if not hasattr(ws_object, WorkflowPolicyConfig_id):    
                    try:
                        ws_object.manage_addProduct['CMFPlacefulWorkflow'].\
                                                manage_addWorkflowPolicyConfig()
                        wfp = getattr(ws_object, WorkflowPolicyConfig_id)
                        wfp.setPolicyIn(WORKSPACE_POLICY_ID)
                        wfp.setPolicyBelow(WORKSPACE_POLICY_ID)
                        ws_object.reindexObjectSecurity()
                        logging.info('Finished configuring %s workflow policy',
                        ws_object.getId())
                    except Exception, e:
                        logging.error('Unable to configure workflow policy for %s: @@ %s', 
                        ws_object.getId(), e)
                else:
                    logging.info('The workspace %s already has a placeful configuration',
                    ws_object.getId())
        else:
            logging.error('Unable to acquire catalog tool')
    else:
        logging.error('Unable to acquire placeful workflow tool')
    
    return
